//
//  ProjectConfig.m
//  QinjinProject
//
//  Created by Michael on 14-9-12.
//  Copyright (c) 2014年 ___Michael___. All rights reserved.
//

#import "ProjectConfig.h"
#import "AFNetworkReachabilityManager.h"
#import "LoginViewController.h"


@interface ProjectConfig()

@end

@implementation ProjectConfig


-(id)init
{
    self = [super init];
    if (self)
    {
        [[AFNetworkReachabilityManager sharedManager] startMonitoring];
        self.dicLocaldata = [[NSMutableDictionary alloc]initWithCapacity:0];
    }
    return self;
}

-(void)getAFNetworkReachabilityStatus
{
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status)
     {
          __weak typeof(self) weakSelf = self;
         switch (status) {
             case AFNetworkReachabilityStatusReachableViaWWAN:
             {
                 //wlan网络
                 [weakSelf getDataversion];
             }
                 break;
             case AFNetworkReachabilityStatusReachableViaWiFi:
             {
                 //wifi网络
                 [weakSelf getDataversion];
             }
                 break;
             default:
                 break;
         }
     }];
}



//得到文件路径
-(NSString*)dataFilePath:(NSString*)fileName
{
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *documentsDiretory = [paths objectAtIndex:0];
    return [documentsDiretory stringByAppendingPathComponent:fileName];
}


-(void)initLocaldata
{
     NSError * error;
    
    // 先读取读取本地数据(防止在网络请求过程操作了关于本地的数据的)
    NSString * filePath = [self dataFilePath:LOCALDATA_FILENAME];
    BOOL fileExist = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
    if (fileExist)
    {
        NSMutableDictionary * arrData = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];
        [self.dicLocaldata addEntriesFromDictionary:arrData];
        
    }else
    {
         //本地有没有保存数据(因为第一次可能没有保存数据)读取文件并保存到本地
        NSString *strPath = [[NSBundle mainBundle] pathForResource:@"LocaldataPart" ofType:@"json"];
        NSData *jdata = [[NSData alloc]initWithContentsOfFile:strPath];
        
        id jsonObject =  [NSJSONSerialization JSONObjectWithData:jdata options:NSJSONReadingMutableLeaves error:&error];
       //  NSLog(@"==%@",jsonObject);
        if ([jsonObject isKindOfClass:[NSDictionary class]])
        {
            [self.dicLocaldata addEntriesFromDictionary:jsonObject];
            [self.dicLocaldata writeToFile:filePath atomically:YES];
        }

    }

   //根据网络情况获取数据
    [self getAFNetworkReachabilityStatus];
}


-(void)getDataversion
{
    //获取版本
    [[HttpClient manager]GET:@"/dataversion"
                  parameters:nil
                     success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         id objectData = [responseObject objectForKey:requestDataKey];
         if ([objectData isKindOfClass:[NSDictionary class]])
         {
            // NSLog(@"==%@",objectData);
             NSString * strNewVersion = NullObjToString([objectData objectForKey:@"version"]);
             NSString * strOldVersion = @"";
             
             //获取本地保存的版本信息
             NSString * filePath = [self dataFilePath:dataversion_FILENAME];
             BOOL fileExist = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
             if (fileExist)
             {
                 NSMutableDictionary * dicData = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];
                 strOldVersion = NullObjToString([dicData objectForKey:@"version"]);
             }
             
             //对比是否需要更新
             if(![strNewVersion isEqualToString:strOldVersion] && ![strNewVersion isEqualToString:@""])
             {
                 NSString * strVersionUrl = NullObjToString([objectData objectForKey:@"localdataUrl"]);
                [self getLocaldata:strVersionUrl version:objectData];
                 
             }
         }
         
     } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {}];

}

//获取本地数据
-(void)getLocaldata:(NSString *)strUrl version:(NSMutableDictionary *)versionData
{

    [[HttpClient manager]GET:[NSString stringWithFormat:@"%@",strUrl]
                  parameters:nil
    success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        id objectData = [responseObject objectForKey:requestDataKey];
        NSLog(@"getLocaldata==%@",objectData);
        if ([objectData isKindOfClass:[NSDictionary class]])
        {
            NSString * strsendCodeUrl = NullObjToString([objectData objectForKey:@"sendCodeUrl"]);
            NSString * strloginUrl = NullObjToString([objectData objectForKey:@"loginUrl"]);
            NSString * strbookingListUrl = NullObjToString([objectData objectForKey:@"bookingListUrl"]);
            
            if (![strbookingListUrl isEqualToString:@""] && ![strloginUrl isEqualToString:@""] && ![strsendCodeUrl isEqualToString:@""])
            {
                NSString * filePath = [self dataFilePath:LOCALDATA_FILENAME];
                self.dicLocaldata = [NSMutableDictionary dictionaryWithDictionary:objectData];
                [self.dicLocaldata writeToFile:filePath atomically:YES];
                
                //保存本次更新版本号
                filePath = [self dataFilePath:dataversion_FILENAME];
                [versionData writeToFile:filePath atomically:YES];
            }
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];

}


-(void)readFromUserDataFile
{
    self.dicUserData = [[NSMutableDictionary alloc]initWithCapacity:0];
   [self.dicUserData setObject:@"" forKey:USER_tel];
   [self.dicUserData setObject:@"" forKey:USER_token];
    
    NSString * filePath = [self dataFilePath:USERPROFILE_FILENAME];
    BOOL fileExist = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
    if (fileExist)
    {
      NSMutableDictionary* userDic = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];
      [self.dicUserData addEntriesFromDictionary:userDic];
    }
}

-(void)writeToFile
{
    NSString * filePath = [self dataFilePath:USERPROFILE_FILENAME];
    NSMutableDictionary* userDic = [NSMutableDictionary dictionaryWithDictionary:self.dicUserData];
    [userDic writeToFile:filePath atomically:YES];
}


-(BOOL)isLogin
{
  if ((NullObjToString(self.dicUserData[USER_token])).length > 0)
  {
     return YES;
  }
  return NO;
}


-(BOOL)needLogin
{
    //无token记录-未登陆
    if ((NullObjToString(self.dicUserData[USER_token])).length == 0)
    {
        UIAlertView *alertNeedLogin = [[UIAlertView alloc] initWithTitle:alerTitle message:@"请先登录!" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登录",nil];
        [alertNeedLogin show];
        return YES;
    }
    return NO;
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex != alertView.cancelButtonIndex)
    {
        UINavigationController *navShowing = [[gApp.mainTabBar viewControllers] objectAtIndex:gApp.mainTabBar.selectedIndex];
        
        UIViewController *presenting = [gApp.mainTabBar presentedViewController];
        if (presenting)
        {
            [presenting dismissViewControllerAnimated:NO completion:nil];
        }
        else
        {
            UIViewController *showing = [[navShowing viewControllers] lastObject];//[navShowing visibleViewController];
            presenting = [showing presentedViewController];
            if (presenting)
            {
                [presenting dismissViewControllerAnimated:NO completion:nil];
            }
        }
        
        LoginViewController *loginController = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
        
        MyNavigationController *navLogin = [[MyNavigationController alloc] initWithRootViewController:loginController];
        [gApp.mainTabBar presentViewController:navLogin animated:YES completion:^
         {
            // [navShowing popToRootViewControllerAnimated:NO];
         }];
        
    }
}

-(void)dealloc
{
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}

@end






